import axios from "axios";
const httpInstace = axios.create({
  baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
  timeout: 5000,
});
export default httpInstace;
//请求拦截器
import { useUserData } from "@/store/user";

httpInstace.interceptors.request.use(
  (config) => {
    const userdata = useUserData(); //不能写在config外面否则会报错
    const token = userdata.userData.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (e) => Promise.reject(e)
);

//响应拦截器
import { ElMessage } from "element-plus";
import router from "@/router";
httpInstace.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (e) => {
    // 这里通过拦截器的方式，来发送提示信息，
    // 这个response是拦截到响应码不是200了就会执行这个
    ElMessage({
      type: "warning",
      message: e.response.data.message,
    });
    //401token报错
    if (e.response.status === 401) {
      const userdata = useUserData();
      userdata.clearUserData();
      router.push("/login");
    }
    return Promise.reject(e);
  }
);
